package main

import (
	"gopl.io/ch8/thumbnail"
	"log"
	"time"
)

// makeThumbnails 生成指定文件的缩略图
func makeThumbnails(filenames []string) {
	for _, filename := range filenames {
		_, err := thumbnail.ImageFile(filename)
		if err != nil {
			log.Println(err)
		}
	}
}

// makeThumbnails2 不正确的并行
func makeThumbnails2(filenames []string) {
	for _, filename := range filenames {
		go thumbnail.ImageFile(filename)
	}
}

// makeThumbnails3 并行生成指定文件的缩略图
func makeThumbnails3(filenames []string) {
	ch := make(chan struct{})
	for _, filename := range filenames {
		go func(f string) {
			thumbnail.ImageFile(f)
			ch <- struct{}{}
		}(filename)
	}
	for range filenames {
		<-ch
	}
}

// makeThumbnails4 并行生成指定文件的缩略图
// 任何步骤出错返回一个错误
func makeThumbnails4(filenames []string) error {
	errors := make(chan error)
	for _, filename := range filenames {
		go func(f string) {
			_, err := thumbnail.ImageFile(f)
			errors <- err
		}(filename)
	}
	for range filenames {
		if err := <-errors; err != nil {
			return err // 不正确，goroutine泄漏
		}
	}
	return nil
}

func makeThumbnails5(filenames []string) (thumbfiles []string, err error) {
	type item struct {
		thumbfile string
		err       error
	}
	ch := make(chan item, len(filenames))
	for _, filename := range filenames {
		go func(f string) {
			var it item
			it.thumbfile, it.err = thumbnail.ImageFile(f)
			ch <- it
		}(filename)
	}
	for range filenames {
		it := <-ch
		if it.err != nil {
			return nil, err
		}
		thumbfiles = append(thumbfiles, it.thumbfile)
	}
	return thumbfiles, nil
}

func main() {
	start := time.Now()
	var filenames = []string{"/Users/zhenghc/Desktop/闺女.jpeg"}
	makeThumbnails4(filenames)
	duration := time.Since(start).Seconds()
	log.Println(duration)
}
